package com.bishe.controller;


import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.bishe.entity.User;
import com.bishe.entity.response.LoginInfo;
import com.bishe.entity.response.R;
import com.bishe.entity.response.UserInfo;
import com.bishe.service.UserService;
import io.swagger.annotations.Api;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;


@RestController
@RequestMapping("user")
@Api(tags = "登录")
public class LoginController {

    @Resource
    private UserService userService;

    /**
     * 用户登录（身份认证）
     * Shiro会缓存认证信息
     *
     * @return
     */
    @PostMapping("/login")
    public R login(@RequestBody LoginInfo loginInfo) {
        // 获取当前来访用户的主体对象
        Subject subject = SecurityUtils.getSubject();
        //封装用户的登录数据

        UsernamePasswordToken token = new UsernamePasswordToken(loginInfo.getUsername(), loginInfo.getPassword());
        try{
            subject.login(token); //执行登录的方法，如果没有异常就说明ok了
            String tokenValue = IdUtil.fastSimpleUUID();

            User one = userService.getOne(Wrappers.lambdaQuery(User.class).eq(User::getUsername, loginInfo.getUsername()));
            UserInfo userInfo = new UserInfo();

            if (ObjectUtil.isNotEmpty(one)){
                userInfo.setId(one.getId());
                userInfo.setType(one.getType());
            }
            userInfo.setName(loginInfo.getUsername());
            userInfo.setToken(tokenValue);
            return R.ok("登录成功",userInfo);
        }catch (UnknownAccountException e){ //用户名不存在
            return R.error("用户名不存在！");
        }catch (IncorrectCredentialsException e){
            return R.error("密码错误！");
        }
    }

    /**
     * 退出登录
     * 销毁主体的认证记录（信息），下次访问需要重新认证
     *
     * @return
     */
    @GetMapping("/logout")
    public R logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return R.ok();
    }

}
